import java.util.ArrayList;
import java.util.List;

import javax.swing.tree.TreeNode;

/*
 * @lc app=leetcode.cn id=113 lang=java
 *
 * [113] 路径总和 II
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {

    List<List<Integer>> res=new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if(root==null) return res;
        List<Integer> path=new ArrayList<>();
        dfs(root,targetSum,path);
        return res;
    }
    public void dfs(TreeNode root,int sum,List<Integer> path){
        sum-=root.val;
        path.add(root.val);
        if(root.left==null&&root.right==null&&sum==0){
            res.add(new ArrayList<>(path));//为什么要new？这里需要思考一下
            return;
        }
        if(root.left==null&&root.right==null){
            return;
        }
        if(root.left!=null){
            dfs(root.left, sum, path);
            path.remove(path.size()-1);//回溯
        }
        if(root.right!=null){
            dfs(root.right,sum,path);
            path.remove(path.size()-1);//回溯
        }
        return;
    }
}
// @lc code=end

